#include "heap.h"
void HeapInit(Heap* hp)
{
	hp->a = NULL;
	hp->size = 0;
	hp->capacity = 0;
}

void HeapDestroyed(Heap* hp)
{
	assert(hp);
	free(hp->a);
	hp->a = NULL;
	hp->size = 0;
	hp->capacity = 0;
}
void Swap(HeapDataType* x, HeapDataType* y)
{
	HeapDataType tmp = *x;
	*x = *y;
	*y = tmp;

}
void AdJustUp(HeapDataType* a,int child)
{
	int parent = (child - 1) / 2;
	while (child>0)
	{
		if (a[child] < a[parent])
		{
			//交换
			Swap(&a[child], &a[parent]);
			child = parent;
			parent = (child - 1) / 2;
		}
		else
		{
			break;
		}
	}
}

void HeapPush(Heap* hp, HeapDataType x)
{
	assert(hp);
	//检查容量
	if (hp->size == hp->capacity)
	{
		//扩容
		int  newcapacity = hp->capacity == 0 ? 4 : hp->capacity * 2;
		HeapDataType* tmp = (HeapDataType*)realloc(hp->a, 
							sizeof(HeapDataType)* newcapacity);

		if (tmp == NULL)
		{
			perror("realloc fail");
			exit(-1);
		}

		hp->a = tmp;
		hp->capacity = newcapacity;
	}
	//在size位置存放数据
	hp->a[hp->size] = x;
	hp->size++;
	//printf("size=%d ", hp->size);
	//向上调整 使成为堆
	AdJustUp(hp->a,hp->size-1);
}

void HeapPrintf(Heap* hp)
{
	assert(hp);
	int i = 0;
	for ( i = 0; i < hp->size; i++)
	{
		printf("%d ", hp->a[i]);
	}
	printf("\n");
}

bool HeapEmpty(Heap* hp)
{
	assert(hp);
	return hp->size == 0;
}

void AdJustDown(HeapDataType* a, int size, int parent)
{
	//假设左子树小
	int child = parent * 2 + 1;
	while (child < size)
	{
		//假设错误 右子树小
		if (child+1<size &&a[child] > a[child + 1])
		{
			++child;
		}
		if (a[parent] > a[child])
		{
			Swap(&a[parent], &a[child]);
			parent = child;
			child = parent * 2 + 1;
		}
		else
		{
			break;
		}
	}
}
void HeapPop(Heap* hp)
{
	assert(hp);
	//交换根和最后一个
	Swap(&hp->a[0], &hp->a[hp->size - 1]);
	//删除根
	--(hp->size);
	//向下调整  让其继续属于堆(小堆)
	//printf("szie = %d\n", hp->size);
	AdJustDown(hp->a, hp->size, 0);
}

HeapDataType GetHeapTop(Heap* hp)
{
	assert(hp);
	assert(hp->size>0);
	return hp->a[0];
}

int HeapSize(Heap* hp)
{
	assert(hp);

	return hp->size;
}